package cn.microven.mindmap.oprations;

import cn.microven.mindmap.components.line.MapLine;
import cn.microven.mindmap.components.part.BothSideMapPart;
import cn.microven.mindmap.components.part.LeftMapPart;
import cn.microven.mindmap.components.part.Part;
import cn.microven.mindmap.components.part.RightMapPart;
import cn.microven.mindmap.struture.MindMap;
import javafx.util.Pair;

import java.util.Vector;

public class ChangeLayoutOperation implements Operation {

    private String oldLayout;

    private String newLayout;

    /**
     * 构造方法
     * @param oldLayout 原先布局
     * @param newLayout 新布局
     */
    public ChangeLayoutOperation(String oldLayout, String newLayout) {
        this.oldLayout = oldLayout;
        this.newLayout = newLayout;
    }

    @Override
    public void start(boolean isRedo) {
        MindMap map = MindMap.getInstance();
        BothSideMapPart root = (BothSideMapPart) map.getRoot();


        Vector<Pair<MapLine, Part>> leaves = root.getBothSideLeaves();
        int size = leaves.size();

        if (newLayout.equals("Right")) {
            for (Pair<MapLine, Part> leaf : leaves) {
                RightMapPart right = leaf.getValue().castToRight();
                root.removeLeaf(leaf.getValue());
                root.addRightLeaf(right);
            }
        }
        if (newLayout.equals("Left")) {
            for (Pair<MapLine, Part> leaf : leaves) {
                LeftMapPart left = leaf.getValue().castToLeft();
                root.removeLeaf(leaf.getValue());
                root.addLeftLeaf(left);
            }
        }
        if (newLayout.equals("BothSide")) {
            boolean i = false;
            for (Pair<MapLine, Part> leaf : leaves) {
                i = !i;
                if (i) {
                    RightMapPart right = leaf.getValue().castToRight();
                    root.removeLeaf(leaf.getValue());
                    root.addRightLeaf(right);
                }
                else {
                    LeftMapPart left = leaf.getValue().castToLeft();
                    root.removeLeaf(leaf.getValue());
                    root.addLeftLeaf(left);
                }

            }
        }
        MindMap.getInstance().getRoot().layout();
    }

    @Override
    public void undo() {
        ChangeLayoutOperation clo = new ChangeLayoutOperation(this.newLayout,this.oldLayout);
        clo.start(true);
    }
}
